//
//  RegisterController.m
//  ELife
//
//  Created by feng lu on 11-6-1.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "RegisterController.h"
#import "GTMBase64.h"
#import "M13UserDefaults.h"
#import "AlertView.h"
#include "GDataXMLNode.h"


@implementation RegisterController
@synthesize quickRegister, traditionRegister, passWord1, passWord2, serverButton, textField;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id) init:(id)target
{
    if (self=[super init]) {
        
    }
    delegate = target;
    return self;
}

- (void)dealloc
{
    [quickRegister release]; 
    [traditionRegister release]; 
    [passWord1 release]; 
    [passWord2 release]; 
    [serverButton release]; 
    [textField release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    app = [ELifeAppDelegate App];
    NSString* msg = [app.infoDiction objectForKey:USERINFO_MSGSTATUS];
    
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"RegisterController" owner:self options:nil];
    //NSLog(@"****%@", nib); 
    self.view = [nib objectAtIndex:1];

    if ([msg isEqualToString:@"0"]) {
        UIView* myView = [nib objectAtIndex:3];
        [self.view addSubview:myView];
    }else
    {
        UIView* myView = [nib objectAtIndex:2];
        [self.view addSubview:myView];
    }
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark finish
- (IBAction) finishAction:(id)sender
{
    UIButton* button = (UIButton*)sender;
    if (serverButton.tag == 1042) {
        if (button.tag == 1032) {
            if ([traditionRegister.text length]>0 && [passWord1.text length]>0 && [passWord2.text length]>0) {
                [traditionRegister resignFirstResponder];
                [passWord1 resignFirstResponder];
                [passWord2 resignFirstResponder];
                
                [app startLoginView];
                
                NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:5];
                [param setObject:@"register" forKey:@"action"];
                [param setObject:traditionRegister.text forKey:@"username"];
                [param setObject:passWord1.text forKey:@"password"];
                //traditionRegister.text
                [param setObject:traditionRegister.text forKey:@"phone"];
                [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
                
                NSString* urlRegister = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil], @"user.php?"];
                
                NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlRegister], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
                
                [[app httpRequestPoint]openUrl:dic postParam:param target:self];
                
                [param release];
            }
        }
        else if(button.tag == 1031)
        {
            if ([textField.text length]>0) {
                [app startLoginView];
                
                NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:5];
                [param setObject:@"register_without_passwd" forKey:@"action"];
                [param setObject:textField.text forKey:@"username"];
                [param setObject:textField.text forKey:@"phone"];
                [param setObject:@"0" forKey:@"is_default"];
                //traditionRegister.text
                [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
                
                NSString* urlRegister = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] localizedStringForKey:(@"UserHost") value:@"" table:nil], @"user.php?"];
                
                NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlRegister], @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
                
                [[app httpRequestPoint]openUrl:dic postParam:param target:self];
                
                [param release];

                [textField resignFirstResponder];
            }
            
        }
    }
    else
    {
        [AlertView showAlert:@"允许服务"];
    }
}

- (IBAction) severAction:(id)sender
{
    UIButton* button = (UIButton*) sender;
    if (serverButton.tag == 1041) {
        [button setBackgroundImage:[UIImage imageNamed:@"radiobutton_selected.png"] forState:UIControlStateNormal];
        serverButton.tag = 1042;
    }else
    {
        [button setBackgroundImage:[UIImage imageNamed:@"radiobutton_unselected.png"] forState:UIControlStateNormal];
        serverButton.tag = 1041;
    }
    
}

#pragma mark -
#pragma mark 联网回调

-(void)register_without_passwd:(NSData*) request
{
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:request] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    
    [retStr release];
}
- (void)iRequestFinished:(NSData *)request
{
    
    NSMutableString* retStr = [[NSMutableString alloc]  initWithData:[GTMBase64 decodeData:request] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retStr);
    
    [retStr release];
    
    [app finishLoginView];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:request] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    
    NSArray* children = [rootElement children];
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    NSLog(@"--------body:--------\n%@", bodyElement);
    //某个具体节点的文本内容
    NSString* content = [[[bodyElement elementsForName:@"returncode"]objectAtIndex:0] stringValue];
    if ([content isEqualToString:@"0"]) {
//        [M13UserDefaults setUserDefaults:[NSArray arrayWithObjects:traditionRegister.text, passWord1.text, nil] defaultName:USERINFO_NAMEANDPASSWORD];
        
        [AlertView showAlert:@"注册成功"];
        
        [self.navigationController popViewControllerAnimated:YES];
    }else
        [AlertView showAlert:@"注册失败"];
    
    [doc release];
}


#pragma mark text回调
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
	return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
	[textView resignFirstResponder];
	return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    return YES;
}


@end
